/*
 * BannerView.java
 * business
 *
 * Created by ChenTao on 2017/2/21.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.yidiandao.business.R;
import com.yidiandao.business.constant.Common;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.LogUtils;
import com.yidiandao.business.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ViewPager实现的轮播图广告自定义视图，如京东首页的广告轮播图效果； 既支持自动轮播页面也支持手势滑动切换页面
 */
@Deprecated
public class BannerView extends FrameLayout {

    /**
     * 轮播图图片数量
     */
    private static final int IMAGE_COUNT = 5;

    private Context context;
    /**
     * 用于标志是否在轮播
     */
    private boolean isAutoPlay = false;

    /**
     * 定义轮播图数
     */
    private int count;

    /**
     * 放轮播图片的ImageView 的list
     */
    private List<ImageView> imageViewsList;

    /**
     * 放圆点的View的list
     */
    private List<View> dotViewsList;

    /**
     * 视图容器
     */
    private ViewPager viewPager;

    /**
     * 当前轮播页
     */
    private int currentItem = 0;

    private List<String> mData;

    private SwitchBannerTask mSwitchBannerTask;

    private OnSingleClickListener mOnSingleClickListener;

    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        mData = new ArrayList<>();
    }

    /**
     * 设置数据源
     */
    public void setData(List<String> banners) {
        mData.clear();
        mData.addAll(banners);
        initData(banners);
    }

    /**
     * 开始轮播图切换
     */
    public void startPlay() {
        if (mSwitchBannerTask == null) {
            mSwitchBannerTask = new SwitchBannerTask();
        }
        mSwitchBannerTask.start();
    }

    /**
     * 停止轮播图切换
     */
    public void stopPlay() {
        if (mSwitchBannerTask != null) {
            mSwitchBannerTask.stop();
        }
    }

    public void stop() {
        stopPlay();
        destroyBitmaps();
    }

    /**
     * 初始化相关Data
     */
    private void initData(List<String> banners) {
        imageViewsList = new ArrayList<>();
        dotViewsList = new ArrayList<>();
        // 一步任务获取图片
        new GetListTask().execute(banners);
    }

    /**
     * 初始化Views等UI
     */
    private void initUI(final Context context) {
        if (mData == null || mData.size() == 0) {
            return;
        }

        View inflate = LayoutInflater.from(context).inflate(R.layout.banner_view, this, true);
        final LinearLayout dotLayout = (LinearLayout) inflate.findViewById(R.id.dot_container);
        viewPager = (ViewPager) inflate.findViewById(R.id.viewPager);
        viewPager.setFocusable(true);
        dotLayout.removeAllViews();

        imageViewsList.clear();
        dotViewsList.clear();

        // 点个数与图片特殊相等
        for (int i = 0; i < mData.size(); i++) {

            ImageView view = new ImageView(context);
            view.setTag(mData.get(i));

            //给一个默认图
            if (i == 0) {
                view.setBackgroundResource(R.mipmap.ic_image_normal_2_66);
            }
            view.setScaleType(ScaleType.CENTER_CROP);
            imageViewsList.add(view);
            ImageView dotView = new ImageView(context);
            dotView.setBackgroundResource(R.drawable.dot_normal);

            LinearLayout.LayoutParams params =
                    new LinearLayout.LayoutParams(
                            (int) UIUtils.getDimens(R.dimen.dimen_5),
                            (int) UIUtils.getDimens(R.dimen.dimen_5));
            params.leftMargin = (int) UIUtils.getDimens(R.dimen.dimen_4);
            params.rightMargin = (int) UIUtils.getDimens(R.dimen.dimen_4);
            dotLayout.addView(dotView, params);

            dotViewsList.add(dotView);
            //初始化，进入首页时默认第一个被选中
            dotViewsList.get(0).setBackgroundResource(R.drawable.dot_selected);
        }

        //得到轮播图的数量
        count = imageViewsList.size();

        BannerAdapter pagerAdapter = new BannerAdapter();
        viewPager.setAdapter(pagerAdapter);
        pagerAdapter.notifyDataSetChanged();
        viewPager.addOnPageChangeListener(new BannerPageChangeListener());

        viewPager.setOnTouchListener(
                new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                            case MotionEvent.ACTION_MOVE:
                                stopPlay();
                                break;
                            case MotionEvent.ACTION_UP:
                            case MotionEvent.ACTION_CANCEL:
                                startPlay();
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                });
    }

    /**
     * 销毁ImageView资源，回收内存
     */
    private void destroyBitmaps() {

        for (int i = 0; i < IMAGE_COUNT; i++) {
            try {
                if (imageViewsList == null || imageViewsList.size() == 0) {
                    return;
                }

                ImageView imageView = imageViewsList.get(i);
                if (imageView == null) {
                    return;
                }
                Drawable drawable = imageView.getDrawable();
                if (drawable != null) {
                    //解除drawable对view的引用
                    drawable.setCallback(null);
                }
            } catch (IndexOutOfBoundsException e) {
                LogUtils.v(e.getMessage());
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stop();
    }

    public void setOnSingleClickListener(OnSingleClickListener onSingleClickListener) {
        this.mOnSingleClickListener = onSingleClickListener;
    }

    public interface OnSingleClickListener {
        void onClick(int position);
    }

    /**
     * 填充ViewPager的页面适配器
     */
    private class BannerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            (container).removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            position = position % count;
            ImageView iv = new ImageView(context);

            iv.setScaleType(ScaleType.CENTER_CROP);

            ImageLoader.loadBanner(context, iv, mData.get(position));

            container.addView(iv);

            final int finalPosition = position;
            iv.setOnClickListener(
                    new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mOnSingleClickListener != null) {
                                mOnSingleClickListener.onClick(finalPosition);
                            }
                        }
                    });

            return iv;
        }

        @Override
        public int getCount() {
            return imageViewsList.size() == 1 ? imageViewsList.size() : Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    /**
     * ViewPager的监听器 当ViewPager中页面的状态发生改变时调用
     */
    private class BannerPageChangeListener implements OnPageChangeListener {

        private int oldPosition = 0;

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int position) {
            position = position % count;
            dotViewsList.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
            dotViewsList.get(position).setBackgroundResource(R.drawable.dot_selected);
            oldPosition = position;
        }
    }

    private class SwitchBannerTask implements Runnable {

        @Override
        public void run() {
            if (viewPager != null) {
                try {
                    int currentItem = viewPager.getCurrentItem();
                    viewPager.setCurrentItem(++currentItem);

                    UIUtils.postDelayed(this, Common.BANNER_SWITCH_TIME);
                    isAutoPlay = true;
                } catch (IndexOutOfBoundsException e) {
                    LogUtils.v(e.getMessage());
                }
            }
        }

        public void start() {
            stop();
            UIUtils.postDelayed(this, Common.BANNER_SWITCH_TIME);
        }

        public void stop() {
            UIUtils.removeCallbacks(this);
            isAutoPlay = false;
        }
    }

    /**
     * 异步任务,获取数据
     */
    private class GetListTask extends AsyncTask<List<String>, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(List<String>... param) {
            try {
                //                List<String> banners = param[0];
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                initUI(context);
                // 如果没有在轮播就需要开启轮播
                if (!isAutoPlay) {
                    startPlay();
                }
            }
        }
    }
}
